package com.dylan.shot.head.shiro;

import com.dylan.shot.common.model.Member;
import com.dylan.shot.common.util.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.Realm;

import java.util.Collection;

/**
 * Created by Dylan on 2017/9/12.
 */
public class ShiroHelper {
    private static final String MEMBER_SHIRO_SESSION_NAME = "member";

    private final static String algorithmName = "md5";
    private final static int hashIterations = 2;

    public static String encryptPassword(String sourcePassword) {
        return new SimpleHash(
                algorithmName,
                sourcePassword,
                null,
                hashIterations).toHex();
    }

    /**
     * 清空认证信息缓存,授权信息缓存
     */
    public static void clearCached(Member member) {
        // 只清空当前登录的用户
        if (isLoginedMember(member)) {
            RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            Collection<Realm> realms = securityManager.getRealms();
            for (Realm realm : realms) {
                if (realm instanceof UsernameRealm) {
                    ((UsernameRealm) realm).clearCached();
                } else if (realm instanceof PhoneRealm) {
                    ((PhoneRealm) realm).clearCached();
                } else if (realm instanceof EmailRealm) {
                    ((EmailRealm) realm).clearCached();
                }
            }
        }
    }

    /**
     * 判断该用户是否是当前登录的用户
     */
    public static boolean isLoginedMember(Member member) {
        return member.getMemberId().equals(getCachedMember().getMemberId());
    }

    /**
     * 设置用户信息到缓存
     */
    public static void setCachedMember(Member member) {
        member.setPassword(null);
        SecurityUtils.getSubject().getSession().setAttribute(MEMBER_SHIRO_SESSION_NAME, member);
    }

    /**
     * 获取缓存的用户信息
     */
    public static Member getCachedMember() {
        return (Member) SecurityUtils.getSubject().getSession().getAttribute(MEMBER_SHIRO_SESSION_NAME);
    }


    /**
     * 更新缓存的用户信息,将新信息更新到旧信息上
     */
    public static void updateCachedWorker(Member newMember) {
        Member member = getCachedMember();
        // 只更新当前登录的用户
        if (isLoginedMember(member)) {
            try {
                ObjectUtils.mergeProperties(member, newMember);
                setCachedMember(member);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 移除缓存的用户信息
     */
    public static void removeCachedMember() {
        SecurityUtils.getSubject().getSession().removeAttribute(MEMBER_SHIRO_SESSION_NAME);
    }
}
